package com.ddxz.tool.sql.dynamic;

import com.ddxz.tool.sql.annotation.DdxzDataSource;
import com.ddxz.tool.sql.struct.DataSourceInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @description
 * @author 朱宗刚
 * @date 2019年12月19日
 * @version 1.0.0
 */
@Aspect
@Order(-1)
@Component
public class DdxzDataSourceAspect {
    @Before("@annotation(connect)")
    public void switchDataSource(JoinPoint point, DdxzDataSource connect) {
        DataSourceInfo dsi = (DataSourceInfo)point.getArgs()[0];
        logger.debug("数据源切换到: {}", dsi);
        DdxzDataSourceContextHandler.setDataSource(dsi);
    }

    @After("@annotation(connect)")
    public void restoreDataSource(JoinPoint point, DdxzDataSource connect) {
        DdxzDataSourceContextHandler.clearDataSource();
    }

    private static final Logger logger = LoggerFactory.getLogger(DdxzDataSourceAspect.class);
}
